package com.web.demo.service;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.ResultCallback;
import com.web.demo.model.MessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.Base64;

@Service
@Slf4j
public class ALiService {

    public void chat(MessageDto messageDto, ResponseBodyEmitter emitter) {

        log.info("messageDto:{}", messageDto);
        Generation gen = new Generation();
        QwenParam qwenParam = QwenParam.builder().prompt(messageDto.getMessage()).model("qwen-max-0919").apiKey("sk-60fdf5a27b7b46c9995390a0cc24cb5a").build();

        try {
            gen.streamCall(qwenParam, new ResultCallback<GenerationResult>() {

                @Override
                public void onEvent(GenerationResult generationResult) {
                    log.info("generationResult:{}", generationResult);
                    try {
                        emitter.send(Base64.getEncoder().encodeToString(generationResult.getOutput().getText().getBytes()));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void onComplete() {
                    log.info("onComplete");
                    emitter.complete();
                }

                @Override
                public void onError(Exception e) {
                    log.error("error:", e);
                }
            });
        } catch (Exception e) {
            log.error("chat error:", e);
        }
    }
}
